﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Yipusoft.TownshipEnterprise.BLL;
using System.Collections.Generic;
using Yipusoft.TownshipEnterprise.Model;
using Yipusoft.Common.BLL;
using Yipusoft.SoldierArchives.BLL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Yipusoft.Account.BLL;
using Yipusoft.Account.Model;
using Yipusoft.Common.Model;
using Yipusoft.Common.BLL;
using Yipusoft.SoldierArchives.BLL;
using Yipusoft.SoldierArchives.Model;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;

public partial class TownshipEnterprise_VehicleAdd : System.Web.UI.Page
{

    int _limitwidth = 640;
    int _limitheight = 480;
    String StrDdlValue="";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            GridBind("");
            //ddlTownBasic.Items.Clear();
            //ddlTownBasic.Items.Add("--请选择--");
            //BindArmys();
            BindCar();
        }
	StrDdlValue=ddlTownBasic.SelectedValue.ToString();
    }
    /// <summary>
    /// 绑定支队
    /// </summary>
    /// <param name="departmentID"></param>
    private void GridBind(string departmentID)
    {
        UserInfo userInfo = Yipusoft.Account.BLL.User.GetUser(User.Identity.Name);
        DepartmentInfo department = Department.GetDepartment(userInfo.DepartmentID);
        if (userInfo.DepartmentID.Substring(0, 4) == "1300")
        {
            DepartmentList.DataSource = Yipusoft.Account.BLL.Department.GetList(" (SUBSTRING(DepartmentID, 5, 3) = '000') and DepartmentID<>'1300000' ");
           
        }
        else
        {
            DepartmentList.DataSource = Yipusoft.Account.BLL.Department.GetList(" DepartmentID= '" + department.DepartmentID.Substring(0, 4) + "000' ");
            
        }
      
        this.DepartmentList.DataBind();
        DepartmentListBind();

        //Yipusoft.Account.Model.DepartmentInfo info = Yipusoft.Account.BLL.Department.GetDepartment(Request["DepartmentID"]);
        ////if (info != null)
        ////{
        ////    this.ddlPhotoName.Items.Insert(0, new ListItem(info.FullName, info.FullName));
        ////}

        //this.DptFireType.DataSource = Yipusoft.Common.BLL.CodeItem.GetList2(" GroupID='XFZLB'");
        //this.DptFireType.DataTextField = "ItemName";
        //this.DptFireType.DataValueField = "ItemID";
        //this.DptFireType.DataBind();

        //this.DptLevel.DataSource = Yipusoft.Common.BLL.CodeItem.GetList2(" GroupID='XFZDJ'");
        //this.DptLevel.DataTextField = "ItemName";
        //this.DptLevel.DataValueField = "ItemID";
        //this.DptLevel.DataBind();


        //DepartmentList.Items.Insert(0, new ListItem("请选择单位", "00"));
        //List<DepartmentPhotoInfo> departmentPhotos = DepartmentPhoto.GetPhotoListByDepartmentID(departmentID);
        //gvDepartmentPhoto.DataSource = DepartmentPhoto.GetPhotoListByDepartmentID(departmentID);
        //gvDepartmentPhoto.DataBind();
        if (Request["DepartmentID"] != null)
        {
            if ((!Request["DepartmentID"].Substring(0, 4).Equals("13121")) && (!Request["DepartmentID"].Substring(0, 4).Equals("13131")))
            {
                this.DepartmentList.SelectedValue = Request["DepartmentID"].Substring(0, 4) + "000";
            }
            else
            {
                this.DepartmentList.SelectedValue = Request["DepartmentID"].Substring(0, 5) + "00";
            }
            this.DepartmentList_SelectedIndexChanged(this.DepartmentList, new EventArgs());
            this.DepartmentList.SelectedValue = Request["DepartmentID"];
            // this.txtArmy.Text = DptSmall.SelectedItem.Text;
        }


    }

    /// <summary>
    /// 绑定队伍
    /// </summary>
    private void BindArmys(string DepartmentID)
    {
        ddlTownBasic.Items.Clear();

        List<TownBasicInfo> tblist = TownBasic.GetList("DepartmentID='" + DepartmentID + "'");
        if (tblist.Count > 0)
        {
            ddlTownBasic.DataSource = tblist;
            ddlTownBasic.DataTextField = "Army";
            ddlTownBasic.DataValueField = "id";
            ddlTownBasic.DataBind();
        }
    }

    /// <summary>
    /// 绑定车辆类别
    /// </summary>
    private void BindCar()
    {
        ddlType.Items.Clear();
        ddlType.DataTextField = "ItemName";
        ddlType.DataValueField = "ItemID";
        ddlType.DataSource = CodeItem.GetList2(" GroupID='XFZBLB' and ParentID='10' and ItemID<>'1099' order by SeqID,ItemID ");
        ddlType.DataBind();

        BindClass();
    }

    protected void ddlType_SelectedIndexChanged(object sender, EventArgs e)
    {
        BindClass();
        BindddlDriver();
    }
    private void BindClass()
    {
        ddlClass.Items.Clear();
        ddlClass.DataTextField = "ItemName";
        ddlClass.DataValueField = "ItemID";
        ddlClass.DataSource = CodeItem.GetList2(" GroupID='XFZBLB' and  parentID='" + ddlType.SelectedValue + "' order by ItemID,SeqID ");
        ddlClass.DataBind();
    }

    /// <summary>
    /// 绑定司机
    /// </summary>
    void BindddlDriver()
    {
        //ddlDriver.Items.Clear();
        //if (ddlClass.SelectedValue == "101008" || ddlClass.SelectedValue == "102006" || ddlClass.SelectedValue == "102007" || ddlClass.SelectedValue == "102003" || ddlType.SelectedValue == "1030")
        //{

        //    trDriver.Visible = true;
        //    Soldier soldier = new Soldier();
        //    string where = " DepartmentId='" + UnitList.SelectedValue + "' and isDelete=0 ";
        //    ddlDriver.Items.Add(new ListItem("--------", ""));
        //    ddlDriver.DataSource = soldier.GetSoldiersByWhere(where, "CardID", "desc", 10000, 0);
        //    ddlDriver.DataBind();
        //}
        //else
        //{
        //    trDriver.Visible = false;
        //}
    }
    protected void ddlClass_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    //选择大队--列出所有队伍名称
    protected void UnitList_SelectedIndexChanged(object sender, EventArgs e)
    {
        BingDDLBasicInfo();
    }

    protected void WorkHight6_TextChanged(object sender, EventArgs e)
    {

    }

    //保存
    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Save())
        {
            Prompt.Text = "提示：添加成功！";
            btnSave.Enabled = false;
            //MessageBox.Show("添加成功！");
        }
        else
        {
            Prompt.Text = "提示：添加失败！";
            btnSave.Enabled = true;
            //MessageBox.Show("添加失败！");
        }
    }

    private bool Save()
    {

        if (ddlTownBasic.Items.Count == 0 || ddlTownBasic.SelectedValue == "--请选择--")
        {
            Response.Write("<script language=javascript>alert('请选择队伍名称！')</script>");
            return false;
        }

        //添加
        TownVehiclesInfo info = new TownVehiclesInfo();
        try
        {
            info.VehicleID = Guid.NewGuid();
            info.TownBasicID = new Guid(StrDdlValue);

            info.Address = Address.Text;
            info.AlertInfo = AlertInfo.Text;
            info.CapacityOfFoam = CapacityOfFoam.Text == "" ? -1 : Convert.ToDecimal(CapacityOfFoam.Text);
            info.CapacityOfPowder = CapacityOfPowder.Text == "" ? -1 : Convert.ToDecimal(CapacityOfPowder.Text);
            info.CapacityOfWater = CapacityOfWater.Text == "" ? -1 : Convert.ToDecimal(CapacityOfWater.Text);
            info.ChassisType = ChassisType.Text;
            info.MaxPressure = ConstantPressure.Text == "" ? -1 : Convert.ToDecimal(ConstantPressure.Text);
            info.DateProduc = DateProduc.Text == "" ? DateTime.MaxValue : Convert.ToDateTime(DateProduc.Text);
            info.DatePurchase = DatePurchase.Text == "" ? DateTime.MaxValue : Convert.ToDateTime(DatePurchase.Text);

            
            info.EngineType = EngineType.Text;
            //info.FlowRate = StringToDecimal(FlowRate.Text);
            info.Life = StringToInt(Life.Text);
            info.Manufacturer = Manufacturer.Text;
            info.MaxPower = StringToDecimal(MaxPower.Text);
            info.MaxSpeed = StringToDecimal(MaxSpeed.Text);
            info.MaxTorque = StringToDecimal(MaxTorque.Text);
            info.MostUse = MostUse.Text;
            info.OtherParameters = OtherParameters.Text;
            info.Passenger = StringToInt(Passenger.Text);
            info.Phone = Phone.Text;
            info.Price = StringToDecimal(Price.Text);
            //info.State = rblState.SelectedValue;
            info.TimeLastModified = DateTime.Now;
            info.TotalWeight = StringToDecimal(TotalWeight.Text);
            info.UseMethod = UseMethod.Text;
            info.VehicleClass = ddlClass.SelectedValue;
            info.VehicleMode = VehicleMode.Text;
            info.VehicleName = VehicleName.Text;
            info.NumberPlate = NumberPlate.Text;
            info.WorkHeight = StringToDecimal(WorkHeight.Text);
            info.Wlan = Convert.ToInt32(Wlan.Checked);
            info.VehicleWidth = StringToDecimal(VehicleWidth.Text);
            info.VehicleLength = StringToDecimal(VehicleLength.Text);
            info.VehicleHeight = StringToDecimal(VehicleHeight.Text);
            //info.soldierCount = StringToInt("0");
            info.RadioNO = RadioNO.Text;
            info.PumpType = PumpType.Text;
            info.PumpFlux = StringToDecimal(PumpFlux.Text);
            info.MaxDrinkDepth = StringToDecimal(MaxDrinkDepth.Text);
            info.VehicleNum = Number.Text.ToString();
        }
        catch
        {
            Response.Write("<script language=javascript>alert('填写错误！')</script>");
        }

        //添加照片--数据库
        TownPicsInfo pic = new TownPicsInfo();
        pic.id = Guid.NewGuid();
        pic.TownBasicInfoID = info.VehicleID;

        //保存图片
        HttpFileCollection files = HttpContext.Current.Request.Files;
        HttpPostedFile file = files.Get("ctl00$ContentPlaceHolder1$Picture");
        string path = string.Empty;
        string picName = DateTime.Now.ToString("yyyyMMddHHmmssff");
        bool img = SaveImg(picName, "4", file, out path);
        if (!img)
	{
		
            return false;
	}
        else
        {
            pic.PicDescript = "";
            pic.PicPath = path;
            pic.TownPicstypeID = "g";
            bool b1 = TownPics.Insert(pic);
            if (!b1)
            {

                string allPath = Request.MapPath("") + "\\" + @path;
                try
                {
                    File.Delete(allPath);
                }
                catch
                { }
                Response.Write("<script language=javascript>alert('图片上传失败！')</script>");
                return false;
            }
        }
        info.Picture = path;
        bool b_add = TownVehicles.Insert(info);
        if (b_add)
        {
            //司机
            //if (ddlDriver.SelectedValue != "")
            //{
            //    VehicleDriverInfo driver = new VehicleDriverInfo();
            //    driver.Id = Guid.NewGuid();
            //    driver.VehicleId = id;
            //    driver.SetDate = DateTime.Now;
            //    driver.SetUserId = Page.User.Identity.Name;
            //    driver.SoldierId = new Guid(ddlDriver.SelectedValue);
            //    VehicleDriver.Insert(driver);
            //}
            //EventLogInfo log = new EventLogInfo();
            //log.EventTime = DateTime.Now;
            //log.EventType = 1;
            //log.EventData = "添加新记录";
            //log.ItemID = id.ToString();
            //log.ItemName = "Vehicle";
            //log.ItemFullUrl = "Vehicle/VehicleNew.aspx";
            //log.CreatedBy = Context.User.Identity.Name;
            //log.CreatedTime = DateTime.Now;
            //log.UserIP = Request.UserHostAddress;
            //EventLog.Insert(log);

            Prompt.Text = "提示：添加成功！";
            return true;
        }
        else
        {
            Prompt.Text = "提示：添加失败！";
            return false;
        }
        return false;
    }

    DateTime StringToDateTime(string strDate)
    {
        return strDate == "" ? DateTime.MaxValue : Convert.ToDateTime(strDate);
    }

    decimal StringToDecimal(string str)
    {
        return str == "" ? -1 : Convert.ToDecimal(str);
    }

    int StringToInt(string str)
    {
        return str == "" ? -1 : Convert.ToInt32(str);
    }

    string DateTimeToString(DateTime dt)
    {
        return dt.Year == 9999 ? "" : dt.ToString("yyyy-MM-dd");
    }

    string DecimalToString(Decimal de)
    {
        return de == -1 ? "" : de.ToString();
    }

    string IntToString(int data)
    {
        return data == -1 ? "" : data.ToString();
    }


    //选择支队-列出大队
    protected void DepartmentList_SelectedIndexChanged(object sender, EventArgs e)
    {

        DepartmentListBind();
        
    }


    /// <summary>
    /// 绑定县
    /// </summary>
    void DepartmentListBind()
    {
        if (DepartmentList.Items.Count <= 0)
            return;
        if (DepartmentList.SelectedValue.ToString() == "")
            return;

        UnitList.Items.Clear();
        string strWhere = "DepartmentID like '" + DepartmentList.SelectedValue.Substring(0, 4) + "2%' and   SUBSTRING(DepartmentID, 5, 1)<>'0' ";
        List<DepartmentInfo> list = Department.GetList(strWhere);
        foreach (DepartmentInfo dpt in list)
        {
            dpt.ShortName = dpt.ShortName.Replace("消防科", "");
            dpt.ShortName = dpt.ShortName.Replace("大队", "");
            dpt.ShortName = dpt.ShortName.Replace("消防", "");
        }
        UnitList.DataSource = list;
        UnitList.DataBind();
        BingDDLBasicInfo();
    }

    /// <summary>
    /// 绑定消防队
    /// </summary>
    void BingDDLBasicInfo()
    {
        ddlTownBasic.Items.Clear();
        string strWhere = " DepartmentID='" + UnitList.SelectedValue.ToString() + "'";
        List<TownBasicInfo> list = TownBasic.GetList(strWhere);
        if (list.Count == 0)
        {
            btnSave.Enabled = false;
            Prompt.Text = "错误：没有可添加信息的消防队，请先添加此地区消防队。";
            ddlTownBasic.Items.Add("此地区没有消防队");

            string colorStr = System.Drawing.ColorTranslator.ToHtml(Color.Red);
            ddlTownBasic.Items[0].Attributes.Add("style", "color:" + colorStr);
            return;
        }
        else
        {
            btnSave.Enabled = true;
            Prompt.Text = "";
            ddlTownBasic.DataSource = list;
            ddlTownBasic.DataBind();
        }
    }

    /// <summary>
    /// 上传图片
    /// </summary>
    /// <param name="name1">图片名称，不包含扩展名</param>
    /// <param name="typepath">图片分类目录TownItems表id</param>
    /// <param name="localPath">返回站点相对路径和文件名</param>
    /// <param name="postedFile">单独文件上传流</param>
    /// <returns></returns>
    private bool SaveImg(string name1, string typepath, HttpPostedFile postedFile, out string localPath)
    {
        //HttpFileCollection files = HttpContext.Current.Request.Files;
        System.Text.StringBuilder strMsg = new System.Text.StringBuilder();

        bool fileOk = false;



        //HttpPostedFile postedFile = files[0];

        string fileName, fileExtension;
        fileName = System.IO.Path.GetFileName(postedFile.FileName);
        if (fileName != "")
        {

            fileExtension = System.IO.Path.GetExtension(fileName);
            String[] allowedExtensions = { ".jpg" ,".bmp",".gif"};
            for (int i = 0; i < allowedExtensions.Length; i++)
            {
                if (fileExtension.ToLower() == allowedExtensions[i])
                {
                    fileOk = true;

                    break;
                }
            }
        }
        if (fileOk)
        {

            //Bitmap bm = new Bitmap(path);
            //本地image文件夹路径
            string sPath = System.Web.HttpContext.Current.Request.MapPath("UpLoadImages\\" + typepath + "\\");
            //文件扩展名
            fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
            //随机文件名
            Random rnd = new Random();
            // string newName = DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "") + rnd.Next(1000).ToString();
            string newName = name1;
            localPath = "UpLoadImages\\" + typepath + "\\" + newName + fileExtension;
            // postedFile.SaveAs(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/") + newName + fileExtension);

            // Bitmap bmp = new Bitmap(postedFile.InputStream);



            double width = 1024;
            double height = 768;
            //从文件取得图片对象
            System.Drawing.Image image = System.Drawing.Image.FromStream(postedFile.InputStream);
            System.Double NewWidth, NewHeight;

            if (image.Width > image.Height)
            {
                NewWidth = width;
                NewHeight = image.Height * (NewWidth / image.Width);
            }
            else
            {
                NewHeight = height;
                NewWidth = (NewHeight / image.Height) * image.Width;
            }

            if (NewWidth > width)
            {
                NewWidth = width;
            }
            if (NewHeight > height)
            {
                NewHeight = height;
            }

            //取得图片大小
            System.Drawing.Size size = new Size((int)NewWidth, (int)NewHeight);
            //新建一个bmp图片
            System.Drawing.Image bitmap = new System.Drawing.Bitmap(size.Width, size.Height);
            //新建一个画板
            System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap);
            //设置高质量插值法
            g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
            //设置高质量,低速度呈现平滑程度
            g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            //清空一下画布
            g.Clear(System.Drawing.Color.White);
            //在指定位置画图
            g.DrawImage(image, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height),
            new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
            System.Drawing.GraphicsUnit.Pixel);

            //保存高清晰度的缩略图
            bitmap.Save(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages\\" + typepath + "\\") + newName + fileExtension, ImageFormat.Jpeg);

            // bmp.Save(System.Web.HttpContext.Current.Request.MapPath("UpLoadImages/") + newName + fileExtension, ImageFormat.Jpeg);


            return true;

        }
        else
        {
            //提示
            localPath = "";
            return false;
        }

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        string id = "fffb7b19-47cf-4131-86f4-545ae95cc139";
        Response.Redirect("VehicleEdit.aspx?id=" + id + "");
    }
}
